import React, { useState, useEffect, useMemo, memo } from 'react'

// function Son({ person }) {
//     return (
//         <div>
//             劳资是子组件
//             <br />
//             {JSON.stringify(person)}
//             {console.log("Son re-render")}
//         </div>
//     )
// }

// useMemo传递的数据person如果没有发生变化 则不更新person props
const Son = memo(
    ({ person }) => {
        return (
            <div>
                劳资是子组件
                <br />
                {JSON.stringify(person)}
                {console.log("Son re-rendered")}
            </div>
        )
    }
)

function UseMemoDemo() {
    const [count, setCount] = useState(0)
    const [age, setAge] = useState(20)

    // const person = {
    //     name: "张全蛋",
    //     age
    // }

    /* age发生更新时 给person重新赋值 */
    const person = useMemo(
        () => {
            console.log("memo数据更新");

            // 给person重新赋值
            return { name: "张全蛋", age }
        },
        [age]
    )

    return (
        <div>
            {count} {" "}
            <button onClick={() => {
                setCount(count + 1)
            }}>+</button>
            <br />

            {age} {" "}
            <button onClick={() => {
                setAge(age + 1)
            }}>age++</button>

            <br />
            <Son person={person} />
        </div>
    )
}

export default UseMemoDemo
